<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>websocket1</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
</head>
<style type="text/css">
    #messdiv{
        width:800px;
        border:2px solid pink;
        height: 800px;
        margin: 0px auto;
        border-radius:20px;
        margin-bottom: 20px;
        /*float:left;*/
        position:relative;
    }
    .title{
        text-align: center;
        border-bottom: 2px solid pink;
    }
    .content{

    }
    .handle{
            width:100%;
            height:70px;
             position:absolute;
            bottom:2%;
            text-align: center;
            border-top: 1px solid pink;
            line-height: 70px;
    }
    #message{
        width:40%;
        height:30px;
        border-radius: 15px;
        border: 1px solid pink;
    }
    #send{
        background-color: #4CAF50;
        height: 30px;
        width: 50px;
        text-align: center;
        /*color: #ff5722;*/
        font-weight: 600;
        font-size: 15px;
        border:none;
        border-radius: 5px;
        cursor:pointer;
    }
</style>
<body>
    <div id='messdiv'>
        <h1 class="title">WEBSOCKET聊天</h1>
        <div class="content"></div>
        <div class="handle">
            <input type="text" name="" id='message'>
            <input type="submit" id='send' value="send"> 
        </div>
    </div>

</body>
<script>
// var socket = new WebSocket('ws://127.0.0.1:9000');
// var url = "ws://127.0.0.1:8888";
var url = "ws://45.40.207.184:8888";
//兼容 FireFox
if ("WebSocket" in window) {
    socket = new WebSocket(url);
} else if ("MozWebSocket" in window) {
    socket = new MozWebSocket(url);
}
socket.onopen = function(event) {
    console.log('连接成功!');
    socket.send("连接成功!\n");
};
socket.onmessage = function(event) {//当客户端收到服务端发来的消息时，会触发onmessage事件，参数event.data中包含server传输过来的数据
    var content = event.data;//获取消息
    if (content.length > 0) {
        var str ='<p>'+content+'</p>';
        $('.content').append(str);
        console.log("客户端回复 :"+content);
    }
};
socket.onclose = function(evt)
{
  console.log("WebSocketClosed!");
};
socket.onerror = function(evt)
{   
  console.log("WebSocketError!");
};
var send = document.getElementById('send');
$('#send').on('click',function(){
    var content = document.getElementById('message').value;
    console.log('我说: '+content);
    socket.send(content);
    console.log('发送成功!');
})
$(document).keypress(function(e) {  

       if((e.keyCode || e.which)==13) {  
           $("#send").click();  //login_btn登录按钮的id
       }  

   }); 

</script>
</html>
